<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Admin\Data\Config;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Goods\Entity\GoodsAttribute;
use Goods\Entity\GoodsAttributeValue;
use Goods\Entity\GoodsClass;
use Goods\Entity\GoodsCustom;
use Goods\Entity\GoodsDiscount;
use Goods\Entity\GoodsImage;
use Goods\Entity\GoodsInAttribute;
use Goods\Entity\GoodsInSpecGoods;
use Goods\Entity\GoodsInSpecGroupTag;
use Goods\Entity\GoodsInSpecImage;
use Goods\Entity\GoodsInWholesale;
use Goods\Entity\GoodsStock;
use Goods\Entity\GoodsTag;
use Goods\Entity\GoodsTagGroup;
use Goods\Entity\GoodsVirtual;
use Goods\Form\GoodsEditPriceForm;
use Goods\Form\GoodsForm;
use Goods\Form\GoodsImageForm;
use Goods\Form\GoodsVirtualForm;
use Goods\Form\SearchGoodsForm;
use Goods\Service\GoodsCustomManager;
use Goods\Service\GoodsDiscountManager;
use Goods\Service\GoodsGroupPriceManager;
use Goods\Service\GoodsImageManager;
use Goods\Service\GoodsInAttributeManager;
use Goods\Service\GoodsInClassManager;
use Goods\Service\GoodsInSpecGoodsGroupPriceManager;
use Goods\Service\GoodsInSpecGoodsManager;
use Goods\Service\GoodsInSpecGroupTagManager;
use Goods\Service\GoodsInSpecImageManager;
use Goods\Service\GoodsInTagManager;
use Goods\Service\GoodsInWholesaleManager;
use Goods\Service\GoodsManager;
use Goods\Service\GoodsSalesRecordManager;
use Goods\Service\GoodsStockManager;
use Goods\Service\GoodsVirtualManager;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use User\Entity\UserGroup;
use Laminas\Filter\StaticFilter;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;

class IndexController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $goodsManager;
    private $goodsImageManager;
    private $goodsStockManager;
    private $goodsDiscountManager;
    private $goodsInClassManager;
    private $goodsCustomManager;
    private $goodsInTagManager;
    private $goodsInAttributeManager;
    private $goodsInSpecGroupTagManager;
    private $goodsInSpecGoodsManager;
    private $goodsInSpecImageManager;
    private $goodsInWholesaleManager;
    private $goodsVirtualManager;
    private $goodsSalesRecordManager;
    private $goodsGroupPriceManager;
    private $goodsInSpecGoodsGroupPriceManager;

    public function __construct(
        Translator          $translator,
        EntityManager       $entityManager,
        GoodsManager        $goodsManager,
        GoodsImageManager   $goodsImageManager,
        GoodsStockManager   $goodsStockManager,
        GoodsDiscountManager $goodsDiscountManager,
        GoodsInClassManager $goodsInClassManager,
        GoodsCustomManager  $goodsCustomManager,
        GoodsInTagManager   $goodsInTagManager,
        GoodsInAttributeManager $goodsInAttributeManager,
        GoodsInSpecGroupTagManager $goodsInSpecGroupTagManager,
        GoodsInSpecGoodsManager $goodsInSpecGoodsManager,
        GoodsInSpecImageManager $goodsInSpecImageManager,
        GoodsInWholesaleManager $goodsInWholesaleManager,
        GoodsVirtualManager $goodsVirtualManager,
        GoodsSalesRecordManager $goodsSalesRecordManager,
        GoodsGroupPriceManager $goodsGroupPriceManager,
        GoodsInSpecGoodsGroupPriceManager $goodsInSpecGoodsGroupPriceManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->goodsManager     = $goodsManager;
        $this->goodsImageManager= $goodsImageManager;
        $this->goodsStockManager= $goodsStockManager;
        $this->goodsDiscountManager = $goodsDiscountManager;
        $this->goodsInClassManager  = $goodsInClassManager;
        $this->goodsCustomManager   = $goodsCustomManager;
        $this->goodsInTagManager    = $goodsInTagManager;
        $this->goodsInAttributeManager      = $goodsInAttributeManager;
        $this->goodsInSpecGroupTagManager   = $goodsInSpecGroupTagManager;
        $this->goodsInSpecGoodsManager      = $goodsInSpecGoodsManager;
        $this->goodsInSpecImageManager      = $goodsInSpecImageManager;
        $this->goodsInWholesaleManager      = $goodsInWholesaleManager;
        $this->goodsVirtualManager  = $goodsVirtualManager;
        $this->goodsSalesRecordManager      = $goodsSalesRecordManager;
        $this->goodsGroupPriceManager       = $goodsGroupPriceManager;
        $this->goodsInSpecGoodsGroupPriceManager = $goodsInSpecGoodsGroupPriceManager;
    }

    /**
     * 商品列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchGoodsForm();
        $searchForm->get('goods_state')->setValueOptions(Common::goodsState($this->translator));
        $searchForm->get('goods_type')->setValueOptions(Common::goodsType($this->translator));
        $searchForm->get('class_id')->setValueOptions($this->goodsPlugin()->classListOptions($this->translator->translate('选择分类')));
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query      = $this->entityManager->getRepository(Goods::class)->findAllGoods($search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return [
            'goodsList' => $paginator,
            'searchForm' => $searchForm,
            'integralCurrencyCon' => Common::configValue('integral_type_1', 'integral')['integralCurrencyCon']
        ];
    }

    /**
     * 添加商品
     * @return array|\Laminas\Http\Response
     */
    public function addAction()
    {
        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);

        $queryData = $this->params()->fromQuery();

        $form = new GoodsForm();
        $form->get('brandId')->setValueOptions($this->goodsPlugin()->goodsBrandOptions());
        $form->get('attributeGroupId')->setValueOptions($this->goodsPlugin()->attributeGroupOptions());
        $form->get('discountUserGroup')->setValueOptions($this->userPlugin()->userGroupOptions('', false));
        $form->get('inClassId')->setValueOptions($this->goodsPlugin()->classValueArray($classList));
        $form->get('goodsWeightConversion')->setValueOptions(Common::weightUnit($this->translator));
        $form->get('goodsState')->setValueOptions(Common::goodsState($this->translator));
        $form->get('goodsType')->setValueOptions(Common::goodsType($this->translator));
        $form->get('discountUserGroupType')->setValueOptions(Common::goodsDiscountUserGroupType($this->translator));
        $form->get('stockShow')->setValueOptions(Common::goodsStockShow($this->translator));
        $form->get('stockOutShow')->setValueOptions(Common::goodsOutStockShow($this->translator));

        $response   = $this->getEventManager()->trigger('goods.add.show', $this, ['form' => $form, 'goodsType' => 'add']);
        $extend     = $response->last();
        if (isset($extend['form'])) $form = $extend['form'];

        if($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if($form->isValid()) {
                $data = $form->getData();

                $this->entityManager->beginTransaction();
                try {
                    //商品基本信息
                    $goodsImageIdArray = $data['goodsImageId'];
                    if($data['defaultImage'] > 0) $data['goodsImageId'] = $data['defaultImage'];
                    $data['goodsUserGroupPrice'] = serialize($postData['goodsUserGroupPrice']);
                    $goodsInfo = $this->goodsManager->addGoods($data);
                    $this->goodsImageManager->editMoreGoodsImageGoodsId($goodsInfo->getGoodsId(), $this->adminCommon()->admin('session_id'));
                    $this->goodsImageManager->updateMoreGoodsImage($goodsImageIdArray);

                    $data['goodsId'] = $goodsInfo->getGoodsId();

                    //商品会员组价格
                    $this->goodsGroupPriceManager->addGoodsGroupPrice($postData['goodsUserGroupPrice'], $data['goodsId']);

                    //商品分类
                    $this->goodsInClassManager->addGoodsInClass($data['inClassId'], $goodsInfo->getGoodsId());

                    //库存
                    $goodsStock= $this->goodsStockManager->addGoodsStock($data);

                    //更新商品基本信息
                    $updateGoods = [];
                    if($data['defaultImage'] <= 0) {
                        $randGoodsImage = $this->entityManager->getRepository(GoodsImage::class)->findOneBy(['goodsId' => $goodsInfo->getGoodsId()]);
                        if($randGoodsImage) $updateGoods['goodsImageId'] = $randGoodsImage->getGoodsImageId();
                    }
                    $updateGoods['stockId'] = $goodsStock->getStockId();

                    //优惠
                    $this->goodsDiscountManager->addGoodsDiscount($data);

                    //规格商品
                    $specGroupArray = $this->goodsInSpecGroupTagManager->addInSpecGroupTag($postData, $goodsInfo->getGoodsId());
                    $specGoodsItemStr = $this->goodsInSpecGoodsManager->addInSpecGoods($postData, $goodsInfo->getGoodsId());
                    $this->goodsInSpecImageManager->addInSpecImage($postData, $specGroupArray['imageGroupId'], $goodsInfo->getGoodsId());
                    $updateGoods['goodsItemStr'] = $specGoodsItemStr;
                    //规格商品会员组价格
                    $this->goodsInSpecGoodsGroupPriceManager->addGoodsInSpecGoodsGroupPrice($postData, $goodsInfo->getGoodsId());

                    //批发
                    $this->goodsInWholesaleManager->addGoodsWholesale($postData, $goodsInfo->getGoodsId());

                    //属性
                    $this->goodsInAttributeManager->addGoodsInAttribute($postData, $goodsInfo->getGoodsId());

                    //标签
                    $tagIdStr = $this->goodsInTagManager->addGoodsInTag($postData,  $goodsInfo->getGoodsId());
                    if(!empty($tagIdStr)) $updateGoods['goodsTagStr'] = $tagIdStr;

                    //商品自定义
                    $this->goodsCustomManager->addGoodsCustom($postData, $goodsInfo->getGoodsId());

                    //销量初始化
                    $this->goodsSalesRecordManager->addGoodsSalesRecord(['goodsId' => $goodsInfo->getGoodsId()]);

                    $this->goodsManager->editGoods($updateGoods, $goodsInfo);

                    $this->getEventManager()->trigger('goods.add.post', $this, ['goodsId' => $goodsInfo->getGoodsId(), 'postData' => $postData]);

                    $this->entityManager->commit();
                    $this->adminCommon()->addOperLog(sprintf($this->translator->translate('商品 %s 添加成功!'), $data['goodsName']), $this->translator->translate('商品管理'));
                } catch (\Exception $e) {
                    $this->entityManager->rollback();
                    $this->flashMessenger()->addWarningMessage($this->translator->translate('商品添加失败!'));
                }
                return $this->redirect()->toRoute('goods', [], ['query' => $queryData]);
            }
        } else $form->get('goodsItem')->setValue($this->goodsPlugin()->createGoodsItem());

        //商品标签
        $goodsTag       = null;
        $goodsTagGroup  = $this->entityManager->getRepository(GoodsTagGroup::class)->findBy([], ['tagGroupSort' => 'ASC', 'tagGroupId' => 'ASC']);
        $goodsTagList   = $this->entityManager->getRepository(GoodsTag::class)->findBy([], ['tagSort' => 'ASC', 'tagId' => 'ASC']);
        if($goodsTagList) foreach ($goodsTagList as $tagValue) {
            $goodsTag[$tagValue->getTagGroupId()][] = ['tagId' => $tagValue->getTagId(), 'tagName' => $tagValue->getTagName()];
        }

        //商品图片
        $goodsImages = $this->entityManager->getRepository(GoodsImage::class)->findBy(['imageCode' => $this->adminCommon()->admin('session_id'), 'goodsId' => 0], ['imageSort' => 'ASC']);

        //会员组
        $userGroup = $this->entityManager->getRepository(UserGroup::class)->findBy([], ['userGroupId' => 'ASC']);

        return [
            'form'          => $form,
            'extend'        => $extend,
            'classList'     => $classList,
            'goodsImages'   => $goodsImages,
            'goodsTagGroup' => $goodsTagGroup,
            'goodsTag'      => $goodsTag,
            'userGroup'     => $userGroup,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol'],
            'queryData'     => $queryData
        ];
    }

    /**
     * 编辑商品
     * @return array|\Laminas\Http\Response
     */
    public function editAction()
    {
        $goodsId = (int) $this->params()->fromRoute('id', -1);

        //商品基本信息
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该商品不存在!'));
            return $this->redirect()->toRoute('goods');
        }
        $goodsInfoArray = $goodsInfo->valuesArray();
        $goodsInfoArray['goodsWeightConversion'] = $goodsInfoArray['goodsWeightConversion'].'|'.$goodsInfoArray['goodsWeightUnit'];

        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);

        //商品库存
        $goodsStock = $this->entityManager->getRepository(GoodsStock::class)->findOneBy(['goodsId' => $goodsId]);

        //商品优惠
        $goodsDiscount = $this->entityManager->getRepository(GoodsDiscount::class)->findOneBy(['goodsId' => $goodsId]);

        $queryData = $this->params()->fromQuery();
        $queryData['page'] = $queryData['sPage'];unset($queryData['sPage']);

        $form = new GoodsForm();
        $form->get('brandId')->setValueOptions($this->goodsPlugin()->goodsBrandOptions());
        $form->get('attributeGroupId')->setValueOptions($this->goodsPlugin()->attributeGroupOptions());
        $form->get('discountUserGroup')->setValueOptions($this->userPlugin()->userGroupOptions('', false));
        $form->get('inClassId')->setValueOptions($this->goodsPlugin()->classValueArray($classList));
        $form->get('goodsWeightConversion')->setValueOptions(Common::weightUnit($this->translator));
        $form->get('goodsState')->setValueOptions(Common::goodsState($this->translator));
        $form->get('goodsType')->setValueOptions(Common::goodsType($this->translator));
        $form->get('discountUserGroupType')->setValueOptions(Common::goodsDiscountUserGroupType($this->translator));
        $form->get('stockShow')->setValueOptions(Common::goodsStockShow($this->translator));
        $form->get('stockOutShow')->setValueOptions(Common::goodsOutStockShow($this->translator));

        $response   = $this->getEventManager()->trigger('goods.edit.show', $this, ['form' => $form, 'goodsType' => 'edit', 'goodsId' => $goodsId]);
        $extend     = $response->last();
        if (isset($extend['form'])) $form = $extend['form'];

        if($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();

                $this->entityManager->beginTransaction();
                try {
                    //标签
                    $data['goodsTagStr'] = $this->goodsInTagManager->editGoodsInTag($postData, $goodsId);

                    //商品基本信息
                    $goodsImageIdArray      = $data['goodsImageId'];
                    $data['goodsImageId']   = $data['defaultImage'];
                    $data['goodsUserGroupPrice'] = serialize($postData['goodsUserGroupPrice']);
                    $goodsInfo = $this->goodsManager->editGoods($data, $goodsInfo);

                    //更新图片
                    $this->goodsImageManager->editMoreGoodsImageGoodsId($goodsId, $this->adminCommon()->admin('session_id'));
                    $this->goodsImageManager->updateMoreGoodsImage($goodsImageIdArray);

                    //商品会员组价格
                    $this->goodsGroupPriceManager->editGoodsGroupPrice($postData['goodsUserGroupPrice'], $goodsId);

                    //商品分类
                    $this->goodsInClassManager->editGoodsInClass($data['inClassId'], $goodsId);

                    //商品库存
                    $this->goodsStockManager->editGoodsStock($data, $goodsStock);

                    //商品优惠
                    $this->goodsDiscountManager->editGoodsDiscount($data, $goodsDiscount);

                    //规格商品
                    $specGoodsItemStr   = '';
                    $specGroupArray     = $this->goodsInSpecGroupTagManager->editInSpecGroupTag($postData, $goodsId);
                    if(isset($postData['goodsSpecGroupId']) && !empty($postData['goodsSpecGroupId'])) {
                        $specGoodsItemStr = $this->goodsInSpecGoodsManager->editInSpecGoods($postData, $goodsId);
                        $this->goodsInSpecImageManager->editInSpecImage($postData, $specGroupArray['imageGroupId'], $goodsId);
                        //规格商品会员组价格
                        $this->goodsInSpecGoodsGroupPriceManager->editGoodsInSpecGoodsGroupPrice($postData, $goodsId);
                    }
                    $this->goodsManager->editGoods(['goodsItemStr' => $specGoodsItemStr], $goodsInfo);
                    //批发
                    $this->goodsInWholesaleManager->editGoodsWholesale($postData, $goodsId);

                    //属性
                    $this->goodsInAttributeManager->editGoodsInAttribute($postData, $goodsInfo->getAttributeGroupId(), $goodsId);

                    //自定义
                    $this->goodsCustomManager->editGoodsCustom($postData, $goodsId);

                    $this->entityManager->commit();
                    $this->getEventManager()->trigger('goods.edit.post', $this, ['goodsId' => $goodsId, 'postData' => $postData]);
                    $this->adminCommon()->addOperLog(sprintf($this->translator->translate('商品 %s 编辑成功!'), $data['goodsName']), $this->translator->translate('商品管理'));
                } catch (\Exception $e) {
                    $this->entityManager->rollback();
                    $this->flashMessenger()->addWarningMessage($this->translator->translate('商品编辑失败!'));
                }

                //保存后继续编辑
                if ($postData['goodsSaveType'] == 'saveReturnEdit') return $this->adminCommon()->toReferer();

                return $this->redirect()->toRoute('goods', [], ['query' => $queryData]);
            }
        }

        //商品优惠赋值处理
        $goodsDiscountArray = $goodsDiscount->valuesArray();
        $goodsDiscountArray['discountStartTime']= $goodsDiscountArray['discountStartTime'] > 0 ? date("Y-m-d H:i:s", $goodsDiscountArray['discountStartTime']) : '';
        $goodsDiscountArray['discountEndTime']  = $goodsDiscountArray['discountEndTime'] > 0 ? date("Y-m-d H:i:s", $goodsDiscountArray['discountEndTime']) : '';
        if(!empty($goodsDiscountArray['discountUserGroup'])) $goodsDiscountArray['discountUserGroup'] = unserialize($goodsDiscountArray['discountUserGroup']);

        $formValue = array_merge($goodsInfoArray, $goodsStock->valuesArray(), $goodsDiscountArray);
        $form->setData($formValue);

        //商品标签
        $goodsTag       = null;
        $goodsTagGroup  = $this->entityManager->getRepository(GoodsTagGroup::class)->findBy([], ['tagGroupSort' => 'ASC', 'tagGroupId' => 'ASC']);
        $goodsTagList   = $this->entityManager->getRepository(GoodsTag::class)->findGoodsTagAndInGoods($goodsId);
        if($goodsTagList) foreach ($goodsTagList as $tagValue) {
            $goodsTag[$tagValue[0]->getTagGroupId()][] = ['inTagId' => $tagValue['inTagId'], 'tagId' => $tagValue[0]->getTagId(), 'tagName' => $tagValue[0]->getTagName()];
        }

        //商品图片
        $goodsImages = $this->entityManager->getRepository(GoodsImage::class)->editorGoodsImageList($goodsId, $this->adminCommon()->admin('session_id'));

        //已选的商品分类
        $selectedClass = $this->goodsPlugin()->selectedGoodsClassArray($goodsId);

        //商品规格
        $specGroupTagArray = $this->entityManager->getRepository(GoodsInSpecGroupTag::class)->findGoodsSpecGroupTag($goodsId);
        $inSpecGoods = $this->entityManager->getRepository(GoodsInSpecGoods::class)->findBy(['goodsId' => $goodsId]);
        //商品规格图片
        $inSpecGoodsImage = $this->entityManager->getRepository(GoodsInSpecImage::class)->findBy(['goodsId' => $goodsId]);

        //商品属性
        $goodsAttributeHtml = '';
        if($goodsInfo->getAttributeGroupId() > 0) {
            $goodsAttributeHtml = $this->attributeHtml($goodsInfo->getAttributeGroupId(), $goodsId);
        }

        //商品批发
        $goodsWholesale     = $this->entityManager->getRepository(GoodsInWholesale::class)->findBy(['goodsId' => $goodsId]);
        $inGoodsWholesale   = [];
        if($goodsWholesale) foreach ($goodsWholesale as $wValue) {
            $inGoodsWholesale[$wValue->getWholesaleKey()] = ['wholesaleStartNum' => $wValue->getWholesaleStartNum(), 'wholesaleEndNum' => $wValue->getWholesaleEndNum(), 'wholesalePrice' => $wValue->getWholesalePrice()];
        }

        //商品自定义
        $inGoodsCustom  = [];
        $goodsCustom    = $this->entityManager->getRepository(GoodsCustom::class)->findBy(['goodsId' => $goodsId]);
        if($goodsCustom) foreach ($goodsCustom as $cValue) {
            $inGoodsCustom[$cValue->getCustomKey()] = ['customTitle' => $cValue->getCustomTitle(), 'customContent' => $cValue->getCustomContent(), 'frontShow' => $cValue->getFrontShow()];
        }

        //会员组
        $userGroup = $this->entityManager->getRepository(UserGroup::class)->findBy([], ['userGroupId' => 'ASC']);

        return [
            'form' => $form,
            'extend'        => $extend,
            'classList'     => $classList,
            'goodsImages'   => $goodsImages,
            'goodsTagGroup' => $goodsTagGroup,
            'goodsTag'      => $goodsTag,
            'userGroup'     => $userGroup,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol'],
            'queryData'     => $queryData,
            'goodsInfo'         => $goodsInfo,
            'selectedClass'     => $selectedClass,
            'specGroupTagArray' => $specGroupTagArray,
            'inSpecGoods'       => $inSpecGoods,
            'inSpecGoodsImage'  => $inSpecGoodsImage,
            'goodsAttributeHtml'=> $goodsAttributeHtml,
            'inGoodsCustom'     => $inGoodsCustom,
            'inGoodsWholesale'  => $inGoodsWholesale
        ];
    }

    /**
     * 修改商品价格
     * @return ViewModel|mixed
     */
    public function editGoodsPriceAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $goodsId = (int) $this->params()->fromQuery('id', -1);

        //商品基本信息
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null) {
            return $this->response->setContent($this->translator->translate('该商品不存在!'));
        }

        $status = false;
        $form   = new GoodsEditPriceForm();
        if($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();
                $this->entityManager->beginTransaction();
                try {
                    if (!isset($postData['specTagIdStr'])) {
                        $data['goodsUserGroupPrice'] = serialize($postData['goodsUserGroupPrice']);
                        //商品会员组价格
                        $this->goodsGroupPriceManager->editGoodsGroupPrice($postData['goodsUserGroupPrice'], $goodsId);
                    }

                    $this->goodsManager->editGoods($data, $goodsInfo);

                    //规格价格修改
                    if (isset($postData['specTagIdStr']) && !empty($postData['specTagIdStr'])) {
                        $this->goodsInSpecGoodsManager->editInSpecGoodsPrice($postData, $goodsId);
                        //规格商品会员组价格
                        $this->goodsInSpecGoodsGroupPriceManager->editGoodsInSpecGoodsGroupPrice($postData, $goodsId);
                    }
                    $this->entityManager->commit();
                    $status = true;
                } catch (\Exception $e) {
                    $this->entityManager->rollback();
                    $this->flashMessenger()->addWarningMessage($this->translator->translate('商品价格修改失败!'));
                }
            }
        }
        $form->setData(['goodsPrice' => $goodsInfo->getGoodsPrice()]);

        //商品规格
        $inSpecGoods    = $this->entityManager->getRepository(GoodsInSpecGoods::class)->findBy(['goodsId' => $goodsId]);
        $goodsTagArray  = $this->entityManager->getRepository(GoodsInSpecGroupTag::class)->findGoodsSpecTagArray($goodsId);

        //会员组
        $userGroup = $this->entityManager->getRepository(UserGroup::class)->findBy([], ['userGroupId' => 'ASC']);

        return $view->setVariables([
            'form'          => $form,
            'userGroup'     => $userGroup,
            'inSpecGoods'   => $inSpecGoods,
            'goodsTagArray' => $goodsTagArray,
            'currencySymbol'=> Common::configValue('default', 'currency')['symbol'],
            'goodsInfo'     => $goodsInfo,
            'status'        => $status
        ]);
    }

    /**
     * 商品批量操作
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateMoreGoodsAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            if (!empty($data['select_id'])) {
                switch ($data['moreUpdateType']) {
                    case 'goodsUp'://上架
                        $this->goodsManager->updateGoodsMoreState($data['select_id']);
                        break;
                    case 'goodsDown'://下架
                        $this->goodsManager->updateGoodsMoreState($data['select_id'], 1);
                        break;
                }
                $this->adminCommon()->addOperLog($this->translator->translate('商品批量处理成功!'), $this->translator->translate('商品管理'));
            } else $this->flashMessenger()->addWarningMessage($this->translator->translate('请选择商品后，再进行操作!'));
        }

        return $this->adminCommon()->toReferer();
    }

    /**
     * 删除商品
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $goodsId = (int) $this->params()->fromRoute('id', -1);

        //商品信息
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该商品不存在!'));
            return $this->adminCommon()->toReferer();
        }

        $this->goodsManager->deleteGoods($goodsInfo);
        $this->goodsGroupPriceManager->deleteGoodsGroupPrice($goodsId);
        $this->goodsCustomManager->deleteGoodsCustomGoodsId($goodsId);
        $this->goodsDiscountManager->deleteGoodsDiscountGoodsId($goodsId);
        $this->goodsInClassManager->delGoodsInClassGoodsId($goodsId);
        $imageArray = $this->goodsImageManager->deleteGoodsImageGoodsId($goodsId);
        if(!empty($imageArray)) $this->adminCommon()->deleteImage($imageArray);
        $this->goodsStockManager->deleteGoodsStockGoodsId($goodsId);
        $this->goodsInAttributeManager->deleteGoodsInAttributeGoodsId($goodsId);
        $this->goodsInSpecGoodsManager->deleteInSpecGoodsId($goodsId);
        $this->goodsInSpecGroupTagManager->deleteInSpecGroupTagGoodsId($goodsId);
        $this->goodsInSpecImageManager->deleteSpecImageGoodsId($goodsId);
        $this->goodsInSpecGoodsGroupPriceManager->deleteGoodsInSpecGoodsGroupPrice($goodsId);
        $this->goodsInTagManager->deleteTagGoodsId($goodsId);
        $this->goodsInWholesaleManager->deleteGoodsWholesaleGoodsId($goodsId);
        $this->goodsSalesRecordManager->deleteGoodsSalesRecord($goodsId);
        $this->goodsVirtualManager->deleteMoreVirtualGoods($goodsId);

        $this->getEventManager()->trigger('goods.delete.post', $this, ['goodsId' => $goodsId, 'imageArray' => $imageArray]);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('商品 %s 删除成功!'), $goodsInfo->getGoodsName()), $this->translator->translate('商品管理'));

        return $this->adminCommon()->toReferer();
    }

    /**
     * 虚拟商品
     * @return array|\Laminas\Http\Response
     */
    public function editVirtualGoodsAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $goodsId = (int) $this->params()->fromRoute('id', -1);

        //商品信息
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null || $goodsInfo->getGoodsType() == 1) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该商品不存在或该商品不是虚拟商品!'));
            return $this->redirect()->toRoute('goods');
        }

        $queryData = $this->params()->fromQuery();
        $queryData['page'] = $queryData['sPage'];unset($queryData['sPage']);

        $form = new GoodsVirtualForm();
        $form->get('virtualGoodsAccountType')->setValueOptions(Common::virtualGoodsType($this->translator));
        $form->get('virtualGoodsPasswordType')->setValueOptions(Common::virtualGoodsType($this->translator));

        $query = $this->entityManager->getRepository(GoodsVirtual::class)->findGoodsVirtualList($goodsId, []);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        //$virtualGoodsList = $this->entityManager->getRepository(GoodsVirtual::class)->findBy(['goodsId' => $goodsId], ['virtualGoodsState' => 'ASC', 'virtualGoodsId' => 'DESC']);

        return ['goodsInfo' => $goodsInfo, 'virtualGoodsList' => $paginator, 'form' => $form, 'queryData' => $queryData];
    }

    /**
     * 虚拟商品批量导入
     * @return mixed
     * @throws \Doctrine\DBAL\DBALException
     */
    public function importAddMoreVirtualGoodsAction()
    {
        @set_time_limit(600);

        $goodsId    = (int) $this->params()->fromRoute('id', -1);
        $excelFile  = $_FILES['excel']['tmp_name'];
        if ($goodsId < 0 || empty($excelFile)) return $this->response->setContent('信息不完整，无法导入');

        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneBy(['goodsId' => $goodsId]);
        if ($goodsInfo == null || $goodsInfo->getGoodsType() == 1) return $this->response->setContent('该商品不存在或者该商品不是虚拟商品');

        $readerXlsx = new Xlsx();
        $spreadsheet = $readerXlsx->load($excelFile);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, false, false, true);

        $rowCount = count($sheetData);
        if ($rowCount == 1) return $this->response->setContent('无导入信息');
        $insertSql = '';
        for ($num = 2; $num <= $rowCount; $num++) {
            if (empty($sheetData[$num]['A']) || empty($sheetData[$num]['B'])) continue;
            $insertSql .= "('".trim($sheetData[$num]['A'])."', 1, '".trim($sheetData[$num]['B'])."', 1, 1, ".(empty($sheetData[$num]['C']) ? 0 : strtotime($sheetData[$num]['C'])).", ".$goodsId."),";
        }
        if (!empty($insertSql)) {
            $insertSql = "INSERT INTO `dbshop_goods_virtual` (`virtual_goods_account`, `virtual_goods_account_type`, `virtual_goods_password`, `virtual_goods_password_type`, `virtual_goods_state`, `virtual_goods_end_time`, `goods_id`) VALUES ".rtrim($insertSql, ',');
            $this->goodsVirtualManager->insertVirtualGoods($insertSql);
        }
        return $this->response->setContent('true');
    }

    /**
     * 获取虚拟商品信息
     * @return JsonModel
     */
    public function ajaxInfoVirtualGoodsAction()
    {
        $goodsId = (int) $this->params()->fromRoute('id', -1);

        //商品信息
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null || $goodsInfo->getGoodsType() == 1) {
            return new JsonModel(['state' => 'false', 'message' => $this->translator->translate('该商品不存在或该商品不是虚拟商品!')]);
        }

        $virtualGoodsId = (int) $this->request->getPost('virtualGoodsId');
        $virtualGoodsInfo = $this->entityManager->getRepository(GoodsVirtual::class)->findOneBy(['virtualGoodsId' => $virtualGoodsId]);
        $data = $virtualGoodsInfo->valuesArray();
        $data['virtualGoodsEndTime'] = $data['virtualGoodsEndTime'] > 0 ? date("Y-m-d", $data['virtualGoodsEndTime']) : '';
        if($virtualGoodsInfo) return new JsonModel(['state' => 'true', 'virtualGoods' => $data]);
        else return new JsonModel(['state' => 'false', 'message' => $this->translator->translate('信息获取失败!')]);
    }

    /**
     * 删除虚拟商品账号信息
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteVirtualGoodsAction()
    {
        $virtualGoodsId = (int) $this->params()->fromRoute('id', -1);
        $virtualGoodsInfo = $this->entityManager->getRepository(GoodsVirtual::class)->findOneBy(['virtualGoodsId' => $virtualGoodsId]);
        if($virtualGoodsInfo && in_array($virtualGoodsInfo->getVirtualGoodsState(), [1, 3])) {
            $this->goodsVirtualManager->deleteVirtualGoods($virtualGoodsInfo);

            $this->adminCommon()->addOperLog(sprintf($this->translator->translate('虚拟商品账号 %s 删除成功!'), $virtualGoodsInfo->getVirtualGoodsAccount()), $this->translator->translate('商品管理'), false);
        }
        return $this->adminCommon()->toReferer();
    }

    /**
     * 虚拟商品更新
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function ajaxUpdateVirtualGoodsAction()
    {
        $goodsId = (int) $this->params()->fromRoute('id', -1);

        //商品信息
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null || $goodsInfo->getGoodsType() == 1) {
            return new JsonModel(['state' => 'false', 'message' => $this->translator->translate('该商品不存在或该商品不是虚拟商品!')]);
        }

        $form = new GoodsVirtualForm();
        $form->get('virtualGoodsAccountType')->setValueOptions(Common::virtualGoodsType($this->translator));
        $form->get('virtualGoodsPasswordType')->setValueOptions(Common::virtualGoodsType($this->translator));

        if($this->getRequest()->isPost()) {
            $postData = $this->params()->fromPost();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = $form->getData();
                $data['virtualGoodsEndTime'] = !empty($data['virtualGoodsEndTime']) ? strtotime($data['virtualGoodsEndTime']) : 0;
                if ($data['virtualGoodsEndTime'] > 0 && $data['virtualGoodsEndTime'] < time()) $data['virtualGoodsState'] = 3;
                if($data['virtualGoodsId'] > 0) {
                    $virtualGoodsInfo = $this->entityManager->getRepository(GoodsVirtual::class)->findOneBy(['virtualGoodsId' => $data['virtualGoodsId']]);
                    if($virtualGoodsInfo) {
                        $virtualGoods = $this->goodsVirtualManager->editVirtualGoods($data, $virtualGoodsInfo);
                        $message = sprintf($this->translator->translate('虚拟商品账号 %s 编辑成功!'), $virtualGoodsInfo->getVirtualGoodsAccount());
                    }
                } else {
                    $virtualGoods = $this->goodsVirtualManager->addVirtualGoods($data, $goodsId);
                    $message = sprintf($this->translator->translate('虚拟商品账号 %s 添加成功!'), $virtualGoods->getVirtualGoodsAccount());
                }
            }
        }
        if(isset($virtualGoods)) {
            $this->adminCommon()->addOperLog($message, $this->translator->translate('商品管理'), false);

            $html = ($data['virtualGoodsId'] > 0 ? '' : '<tr id="virtual-goods-'.$virtualGoods->getVirtualGoodsId().'">');
            $html .= '<td>'.$virtualGoods->getVirtualGoodsAccount().'</td>';
            $html .= '<td>'.$this->goodsPlugin()->getVirtualGoodsType($virtualGoods->getVirtualGoodsAccountType()).'</td>';
            $html .= '<td>'.$virtualGoods->getVirtualGoodsPassword().'</td>';
            $html .= '<td>'.$this->goodsPlugin()->getVirtualGoodsType($virtualGoods->getVirtualGoodsPasswordType()).'</td>';
            $html .= '<td>'.$this->goodsPlugin()->getVirtualGoodsState($virtualGoods->getVirtualGoodsState()).'</td>';
            $html .= '<td>'.($virtualGoods->getVirtualGoodsEndTime() > 0 ? date("Y-m-d", $virtualGoods->getVirtualGoodsEndTime()) : $this->translator->translate('无')).'</td>';
            $html .= '<td>'.$virtualGoods->getOrderSn().'</td>';
            $html .= '<td>';
            $html .= '<a href="javascript:;" onclick="editVirtualGoods('.$virtualGoods->getVirtualGoodsId().')" class="btn btn-xs btn-success"><i class="fa fa-pencil"></i> '.$this->translator->translate('编辑').'</a>';
            $html .= '&nbsp;<a href="javascript:;" onclick="deleteConfirm(\''.$this->translator->translate('您确实要删除该虚拟商品账号信息吗?').'\', \''.$this->url()->fromRoute('goods', ['action'=>'deleteVirtualGoods', 'id'=>$virtualGoods->getVirtualGoodsId()]).'\');" class="btn btn-xs btn-danger"><i class="fa fa-trash"></i> '.$this->translator->translate('删除').'</a>';
            $html .= '</td>';
            $html .= ($data['virtualGoodsId'] > 0 ? '' : '</tr>');
            return new JsonModel(['state' => 'true', 'html' => $html, 'virtualGoodsId' => $virtualGoods->getVirtualGoodsId(), 'type' => ($data['virtualGoodsId'] > 0 ? 'edit' : 'add')]);
        }

        return new JsonModel(['state' => 'false', 'message' => $this->translator->translate('虚拟商品处理失败!')]);
    }

    /**
     * 商品图片上传
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function uploadGoodsImageAction()
    {
        $array = ['jsonrpc' => '2.0', 'state' => 'error', 'message' => $this->translator->translate('图片上传失败')];
        $imageForm = new GoodsImageForm();

        if($this->getRequest()->isPost()) {
            $goodsId = (int) $this->params()->fromRoute('id', 0);

            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $data['goodsId']    = $goodsId;
            $data['imageSlide'] = 1;
            $data['imageCode']  = $goodsId > 0 ? '' : $this->adminCommon()->admin('session_id');
            $data['imageSort']  = 255;
            $imageForm->setData($data);
            if($imageForm->isValid()) {
                $data = $imageForm->getData();
                $imageInfo = $this->goodsImageManager->addGoodsImage($data);
                if($imageInfo) {
                    $array = [
                        'state'         => 'success',
                        'goodsImageId'  => $imageInfo->getGoodsImageId(),
                        'goodsThumbnailImage' => $imageInfo->getGoodsThumbnailImage()
                    ];

                    $response   = $this->getEventManager()->trigger('goods.upload-image.post', $this, ['imageInfo' => $imageInfo]);
                    $imageArray = $response->last();
                    if (!empty($imageArray)) $array = $imageArray;
                }
            } else $array['message'] = implode(',', $imageForm->getMessages('goodsImage'));
        }

        return new JsonModel($array);
    }

    /**
     * 获取编辑器新添加的图片
     * @return JsonModel
     */
    public function ajaxGetEditNewImageAction()
    {
        $goodsId    = (int) $this->params()->fromPost('goodsId', 0);
        $imageIdStr = trim($this->params()->fromPost('imageIdStr'));

        $imageList  = [];
        $goodsImages= $this->entityManager->getRepository(GoodsImage::class)->editorGoodsImageList($goodsId, $this->adminCommon()->admin('session_id'), $imageIdStr);
        if ($goodsImages) foreach ($goodsImages as $imageValue) {
            $imageList[] = ['goodsImageId' => $imageValue->getGoodsImageId(), 'goodsThumbnailImage' => Common::shopImageOss($imageValue->getGoodsThumbnailImage(), 'goods')];
        }

        return new JsonModel(['state' => !empty($imageList) ? 'true' : 'false', 'imageList' => $imageList]);
    }

    /**
     * 商品图片更新
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function ajaxUpdateGoodsImageAction()
    {
        $message = $this->translator->translate('商品图片更新失败!');
        if($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost()->toArray();
            if($data['goodsImageId'] > 0) {
                $goodsImageInfo = $this->entityManager->getRepository(GoodsImage::class)->findOneByGoodsImageId($data['goodsImageId']);
                if($goodsImageInfo) {
                    $this->goodsImageManager->editGoodsImage(['imageSlide' => ($data['imageSlide'] == 'true' ? 1 : 0), 'imageSort' => ($data['imageSort'] > 0 ? $data['imageSort'] : 1)], $goodsImageInfo);
                    $message = $this->translator->translate('商品图片更新成功!');
                }
            }
        }
        return new JsonModel(['message' => $message]);
    }

    /**
     * 商品图片删除
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function ajaxDeleteGoodsImageAction()
    {
        $result = ['state' => 'error', 'message' => $this->translator->translate('商品图片删除失败!')];
        if($this->getRequest()->isPost()) {
            $goodsImageId   = (int) $this->request->getPost('goodsImageId', 0);
            $goodsImageInfo = $this->entityManager->getRepository(GoodsImage::class)->findOneByGoodsImageId($goodsImageId);
            if($goodsImageInfo) {
                $imageArray = [$goodsImageInfo->getGoodsThumbnailImage(), $goodsImageInfo->getGoodsImage()];
                $this->goodsImageManager->deleteGoodsImage($goodsImageInfo);
                $this->adminCommon()->deleteImage($imageArray);

                $this->getEventManager()->trigger('goodsImage.delete.post', $this, ['goodsImageId' => $goodsImageId, 'imageArray' => $imageArray]);

                $result = ['state' => 'success', 'message' => $this->translator->translate('商品图片删除成功!')];
            }
        }
        return new JsonModel($result);
    }

    /**
     * 获取规格组信息
     * @return JsonModel
     */
    public function ajaxGoodsSpecGroupAction()
    {
        $result = ['state' => 'error', 'message' => $this->translator->translate('没有该规格的具体信息!')];
        $tagGroupId = (int) $this->request->getPost('goodsSpecGroupId', 0);
        if($tagGroupId > 0) {
            $tagGroupInfo = $this->entityManager->getRepository(GoodsTagGroup::class)->findOneBy(['tagGroupId' => $tagGroupId, 'isGoodsSpec' => 1]);
            if($tagGroupInfo) {
                $tagList = $this->entityManager->getRepository(GoodsTag::class)->findBy(['tagGroupId' => $tagGroupId], ['tagSort' => 'ASC', 'tagId' => 'ASC']);
                if($tagList) {
                    $html = '<div class="form-group" id="specGroupValueDiv'.$tagGroupId.'">';
                    $html .= '<label class="col-sm-2 control-label">'.$tagGroupInfo->getTagGroupName().' - '.$this->translator->translate('图').' <input type="checkbox" class="checkbox-inline" name="specImage[]" id="specImage'.$tagGroupId.'" onclick="selectSpecImage('.$tagGroupId.')" value="'.$tagGroupId.'"></label>';
                    $html .= '<div class="col-sm-10">';
                    foreach ($tagList as $tagValue) {
                        $html .= '<label class="checkbox-inline">';
                        $html .= '<input type="checkbox" value="'.$tagValue->getTagId().'" name="goodsSpecGroup'.$tagGroupId.'[]" id="goodsSpecGroup'.$tagGroupId.'_'.$tagValue->getTagId().'" title="'.$tagValue->getTagName().'">'.$tagValue->getTagName();
                        $html .= '</label>';
                    }
                    $html .= '</div>';
                    $html .= '</div>';

                    $result = ['state' => 'success', 'html' => $html];
                }
            }
        }
        return new JsonModel($result);
    }

    /**
     * 获取该商品已经上传的图片列表
     * @return JsonModel
     */
    public function ajaxSpecGoodsImageAction()
    {
        $tagId = (int) $this->request->getPost('tagId', 0);
        $specGoodsImageStr  = $this->request->getPost('specGoodsImageStr', '');
        $selectedIdArray    = [];
        if(!empty($specGoodsImageStr)) $selectedIdArray = explode(',', $specGoodsImageStr);

        $tagInfo = $this->entityManager->getRepository(GoodsTag::class)->findOneByTagId($tagId);
        if($tagInfo == null) return new JsonModel(['state' => 'false', 'message' => $this->translator->translate('图片对应的标记信息不存在!')]);

        $imageData = ['state' => 'false', 'message' => $this->translator->translate('暂无图片，请上传商品图片后，再选取对应图片!')];
        $goodsId = (int) $this->params()->fromRoute('id', 0);
        if($goodsId > 0) $where = ['goodsId' => $goodsId];
        else $where = ['goodsId' => 0, 'imageCode' => $this->adminCommon()->admin('session_id')];
        $where['imageSlide'] = 1;

        $imageHtml = '<div>';
        $goodsImageList = $this->entityManager->getRepository(GoodsImage::class)->findBy($where, ['imageSort' => 'ASC']);
        if($goodsImageList) {
            foreach ($goodsImageList as $imageValue) {
                $selectedState = !empty($selectedIdArray) && in_array($imageValue->getGoodsImageId(), $selectedIdArray);
                $imageHtml .= '<div class="col-md-2"><img src="'.$this->goodsPlugin()->goodsImage($imageValue->getGoodsThumbnailImage()).'" alt="" class="img-thumbnail image-list'.($selectedState ? " image-selected-border" : "").'" id="sGoodsImage'.$imageValue->getGoodsImageId().'" data-id="'.$imageValue->getGoodsImageId().'" data-title="'.($selectedState ? 1 : 0).'" onclick="clickSpecImage('.$imageValue->getGoodsImageId().')" style="margin-top: 10px;"></div>';
            }
            $imageData['state']     = 'true';
            $imageData['tagTitle']  = $tagInfo->getTagName();
            $imageData['imageHtml'] = $imageHtml.'</div>';
            unset($imageData['message']);
        }

        return new JsonModel($imageData);
    }

    /**
     * ajax获取商品中属性组对应信息
     * @return JsonModel
     */
    public function ajaxGoodsAttributeGroupAction()
    {
        $array = ['htmlInput' => ''];

        $goodsId = (int) $this->request->getPost('goodsId', 0);
        $attributeGroupId = (int) $this->request->getPost('attributeGroupId', 0);
        if($attributeGroupId > 0) {
            $array['htmlInput'] = $this->attributeHtml($attributeGroupId, $goodsId);
        }

        return new JsonModel($array);
    }


    public function ajaxGoodsSearchAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchGoodsName = trim($this->params()->fromQuery('searchGoodsName'));
        if(!empty($searchGoodsName)) {
            $searchGoodsName = StaticFilter::execute($searchGoodsName, 'StripTags');
            $searchGoodsName = StaticFilter::execute($searchGoodsName, 'HtmlEntities');
            $search['goods_name'] = $searchGoodsName;
        }
        $query = $this->entityManager->getRepository(Goods::class)->findAllGoods($search);
        $goodsList = $this->adminCommon()->shopPaginator($query, $page, 10);

        return $view->setVariables(['goodsList' => $goodsList, 'searchGoodsName' => $searchGoodsName]);
    }

    /**
     * 插入编辑器商品id
     * @return JsonModel|ViewModel
     */
    public function ajaxInsertEditorGoodsAction()
    {
        $goodsId    = (int) $this->params()->fromQuery('goodsId', 0);
        $goodsInfo  = $this->entityManager->getRepository(Goods::class)->findOneBy(['goodsId' => $goodsId]);
        if ($goodsInfo == null) return new JsonModel(['state' => 'error', 'message' => $this->translator->translate('该商品不存在或者已经下架！')]);

        return new JsonModel([
            'state' => 'ok',
            'result'=> [
                'goodsId' => $goodsId
            ]
        ]);
    }

    /**
     * 解析属性
     * @param $attributeGroupId
     * @param int $goodsId
     * @return string
     */
    private function attributeHtml($attributeGroupId, $goodsId = 0)
    {
        $attributeList = $this->entityManager->getRepository(GoodsAttribute::class)->findBy(['attributeGroupId' => $attributeGroupId], ['attributeSort' => 'ASC', 'attributeId' => 'ASC']);
        $attributeValueList = $this->entityManager->getRepository(GoodsAttributeValue::class)->findBy(['attributeGroupId' => $attributeGroupId], ['valueSort' => 'ASC', 'valueId' => 'ASC']);

        $valueArray = [];
        if($attributeValueList) {
            foreach ($attributeValueList as $vValue) {
                $valueArray[$vValue->getAttributeId()][$vValue->getValueId()] = $vValue->getValueName();
            }
        }

        $goodsInAttribute = [];
        if($goodsId > 0) {
            $goodsAttribute = $this->entityManager->getRepository(GoodsInAttribute::class)->findBy(['goodsId' => $goodsId]);
            if(!empty($goodsAttribute)) foreach ($goodsAttribute as $gaValue) {
                $goodsInAttribute[$gaValue->getAttributeId()] = $gaValue->getAttributeBody();
            }
        }

        $html = '';
        if($attributeList) {
            foreach ($attributeList as $aValue) {
                if(!isset($valueArray[$aValue->getAttributeId()]) && !in_array($aValue->getAttributeType(), ['textarea', 'input'])) continue;

                $html .= '<div class="form-group">';
                $html .= '<label class="col-sm-2 control-label">'.$aValue->getAttributeName().'</label>';
                $html .= '<div class="col-sm-6">';
                switch ($aValue->getAttributeType()) {
                    case 'select':
                        if(isset($valueArray[$aValue->getAttributeId()]) && is_array($valueArray[$aValue->getAttributeId()]) && !empty($valueArray[$aValue->getAttributeId()])) {
                            $html .= '<select name="attributeValue[' .$aValue->getAttributeId(). ']" class="form-control"><option value="">'.$this->translator->translate('请选择').'</option>';
                            $selected = 'selected="selected"';
                            foreach ($valueArray[$aValue->getAttributeId()] as $selectKey => $selectValue) {
                                $html .= '<option value="'.$selectKey.'" '.((isset($goodsInAttribute[$aValue->getAttributeId()]) && $goodsInAttribute[$aValue->getAttributeId()] == $selectKey) ? $selected : '').'>'.$selectValue.'</option>';
                            }
                            $html .= '</select>';
                        }
                        break;
                    case 'radio':
                        if(isset($valueArray[$aValue->getAttributeId()]) && is_array($valueArray[$aValue->getAttributeId()]) && !empty($valueArray[$aValue->getAttributeId()])) {
                            $checked = 'checked';
                            foreach ($valueArray[$aValue->getAttributeId()] as $selectKey => $selectValue) {
                                $html .= '<label class="radio-inline"><input type="radio" name="attributeValue['.$aValue->getAttributeId().']" value="'.$selectKey.'" '.((isset($goodsInAttribute[$aValue->getAttributeId()]) && $goodsInAttribute[$aValue->getAttributeId()] == $selectKey) ? $checked : '').'>'.$selectValue.'</label>';
                            }
                        }
                        break;
                    case 'checkbox':
                        if(isset($valueArray[$aValue->getAttributeId()]) && is_array($valueArray[$aValue->getAttributeId()]) && !empty($valueArray[$aValue->getAttributeId()])) {
                            $checkboxChecked = [];
                            if(isset($goodsInAttribute[$aValue->getAttributeId()]) && !empty($goodsInAttribute[$aValue->getAttributeId()])) {
                                $checkboxChecked = explode(',', $goodsInAttribute[$aValue->getAttributeId()]);
                            }
                            foreach ($valueArray[$aValue->getAttributeId()] as $selectKey => $selectValue) {
                                $html .= '<label class="checkbox-inline"><input type="checkbox" value="'.$selectKey.'" name="attributeValue['.$aValue->getAttributeId().'][]" '.(@in_array($selectKey, $checkboxChecked) ? 'checked' : '').'>'.$selectValue.'</label>';
                            }
                        }
                        break;
                    case 'input':
                        $html .= '<input type="text" name="attributeValue['.$aValue->getAttributeId().']" class="form-control" value="'.(isset($goodsInAttribute[$aValue->getAttributeId()]) ? $goodsInAttribute[$aValue->getAttributeId()] : '').'" >';
                        break;
                    case 'textarea':
                        $html .= '<textarea rows="3" name="attributeValue['.$aValue->getAttributeId().']" class="form-control">'.(isset($goodsInAttribute[$aValue->getAttributeId()]) ? $goodsInAttribute[$aValue->getAttributeId()] : '').'</textarea>';
                        break;
                }
                $html .= '</div></div>';
            }
        }
        return $html;
    }
}